﻿<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>生产排产产跟踪表</title>
    <style>
        /* 基础样式保持不变 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Inter', system-ui, sans-serif;
        }

        body {
            background-color: #f9fafb;
            color: #1D2129;
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            width: 95%;
            margin: 0 auto;
            position: relative;
        }

        /* 标题样式 */
        h1 {
            font-size: 2rem;
            font-weight: 700;
            color: #1D2129;
            margin-bottom: 0.5rem;
        }

        h2 {
            font-size: 1.25rem;
            font-weight: 600;
            color: #1D2129;
            margin-bottom: 1rem;
        }

        p {
            color: #4B5563;
            margin-bottom: 1rem;
        }

        /* 卡片样式 */
        .card {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 14px 0 rgba(0, 0, 0, 0.06);
            padding: 1.5rem;
            margin-bottom: 1.5rem;
        }

        /* 生产排产表格卡片特殊样式 */
        .schedule-card {
            padding-bottom: 40px; /* 为底部横向滚动条预留空间 */
            position: relative;
        }

        /* 按钮样式 */
        .btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            padding: 0.5rem 1rem;
            border-radius: 6px;
            font-weight: 500;
            cursor: pointer;
            transition: background-color 0.2s ease;
            gap: 0.5rem;
        }

        .btn-primary {
            background-color: #165DFF;
            color: white;
        }

            .btn-primary:hover {
                background-color: #0F4CD4;
            }

        .btn-secondary {
            background-color: #F3F4F6;
            color: #4B5563;
        }

            .btn-secondary:hover {
                background-color: #E5E7EB;
            }

        /* 表单单样式 */
        .form-group {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            margin-bottom: 1rem;
        }

        .form-label {
            font-size: 0.875rem;
            font-weight: 500;
            color: #4B5563;
        }

        .form-control {
            border: 1px solid #D1D5DB;
            border-radius: 6px;
            padding: 0.5rem 0.75rem;
            font-size: 0.875rem;
            color: #1D2129;
        }

        /* 表格格样式 */
        .excel-table {
            border-collapse: collapse;
            width: 100%;
        }

            .excel-table th,
            .excel-table td {
                border: 1px solid #E5E7EB;
                padding: 4px 8px;
                text-align: left;
                white-space: nowrap;
                font-size: 0.75rem;
                position: relative;
            }

            .excel-table th {
                background-color: #F9FAFB;
                font-weight: 500;
                font-size: 0.7rem;
            }

            .excel-table tr:nth-child(even) {
                background-color: #F9FAFB;
            }

            .excel-table tr:hover {
                background-color: #F3F4F6;
            }

        /* 汇总行样式 */
        .summary-row {
            background-color: #EFF6FF;
            font-weight: 600;
        }

        /* 汇总行与项目数据之间的分隔线 - 已调整位置 */
        .summary-separator {
            border-top: 2px solid #94A3B8;
        }

        /* 工令之间的分隔线 */
        .work-order-separator {
            border-top: 1px solid #CBD5E1;
        }

        /* 自定义表格列宽度 */
        .col-customer-order {
            width: 120px;
            min-width: 120px;
            font-size: 0.75rem;
        }

        .col-work-order {
            width: 70px;
            min-width: 70px;
            font-size: 0.75rem;
        }

        .col-customer {
            width: 100px;
            min-width: 100px;
            font-size: 0.75rem;
        }

        .col-project {
            width: 120px;
            min-width: 120px;
            white-space: normal;
            word-break: break-all;
            font-size: 0.75rem;
        }

        .col-delivery-date {
            width: 90px;
            min-width: 90px;
            font-size: 0.75rem;
        }

        .col-product {
            width: 100px;
            min-width: 100px;
            font-size: 0.75rem;
        }

        .col-order-qty {
            width: 70px;
            min-width: 70px;
            text-align: right;
            font-size: 0.75rem;
        }

        .col-process {
            width: 80px;
            min-width: 80px;
            font-size: 0.75rem;
        }

        .col-category {
            width: 70px;
            min-width: 70px;
            font-size: 0.75rem;
        }

        .col-quantity {
            width: 70px;
            min-width: 70px;
            text-align: right;
            font-size: 0.75rem;
        }

        /* 日期列样式 */
        .date-column {
            min-width: 70px;
            text-align: center;
            font-size: 0.7rem;
        }

        .weekend {
            background-color: #FEF2F2;
        }

        /* 排产数量容器 */
        .schedule-qty-container {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100%;
            padding: 2px 0;
        }

        /* 计划数量样式 */
        .planned-qty {
            font-weight: bold;
            color: #1E40AF;
            margin-bottom: 1px;
            font-size: 0.8em;
        }

        /* 实际数量样式 */
        .actual-qty {
            font-size: 0.6em;
            color: #B91C1C;
        }

        /* 排产状态背景色 */
        .schedule-planned {
            background-color: rgba(255, 235, 59, 0.2); /* 浅黄 - 仅计划 */
        }

        .schedule-actual {
            background-color: rgba(76, 175, 80, 0.2); /* 浅绿 - 实际 */
        }

        /* 状态标签样式 */
        .status-tag {
            display: inline-block;
            padding: 1px 6px;
            border-radius: 9999px;
            font-size: 0.6rem;
            font-weight: 500;
        }

        .status-planned {
            background-color: #E0F2FE;
            color: #0369A1;
        }

        .status-actual {
            background-color: #F0FDF4;
            color: #065F46;
        }

        /* 布局样式 */
        .flex {
            display: flex;
        }

        .flex-wrap {
            flex-wrap: wrap;
        }

        .items-center {
            align-items: center;
        }

        .gap-2 {
            gap: 0.5rem;
        }

        .gap-4 {
            gap: 1rem;
        }

        .mb-4 {
            margin-bottom: 1rem;
        }

        .mb-6 {
            margin-bottom: 1.5rem;
        }

        /* 滚动容器样式优化 - 关键调整 */
        .table-wrapper {
            /* 纵向使用默认滚动条 */
            max-height: 450px; /* 调低表格高度 */
            overflow-y: auto;
            /* 横向滚动使用默认滚动条 */
            overflow-x: auto;
            scrollbar-width: auto; /* 恢复默认滚动条样式 */
            position: relative;
        }

            .table-wrapper::-webkit-scrollbar {
                height: 12px; /* 设置横向滚动条高度 */
                width: auto; /* 恢复默认滚动条样式 */
            }

            /* 美化滚动条 */
            .table-wrapper::-webkit-scrollbar-track {
                background: #f1f1f1;
                border-radius: 4px;
            }

            .table-wrapper::-webkit-scrollbar-thumb {
                background: #c1c1c1;
                border-radius: 4px;
            }

                .table-wrapper::-webkit-scrollbar-thumb:hover {
                    background: #a1a1a1;
                }

        /* 图标替代样式 */
        .icon {
            width: 16px;
            height: 16px;
            display: inline-block;
            background-size: contain;
            background-repeat: no-repeat;
            background-position: center;
        }

        .icon-filter {
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='currentColor' viewBox='0 0 16 16'%3E%3Cpath d='M6 10.5a.5.5 0 0 1 .5-.5h3a.5.5 0 0 1 0 1h-3a.5.5 0 0 1-.5-.5zm-2-3a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5zm-2-3a.5.5 0 0 1 .5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5z'/%3E%3C/svg%3E");
        }

        .icon-refresh {
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='currentColor' viewBox='0 0 16 16'%3E%3Cpath d='M8 3a5 5 0 0 1 5 5v.5a.5.5 0 0 0 1 0V8a6 6 0 0 0-6-6H8.5a.5.5 0 0 0 0 1H8zm2.646 2.646a.5.5 0 0 0-.708 0l-3 3a.5.5 0 1 0 .708.708l1.75-1.75a.5.5 0 0 1 .708 0l2.25 2.25a.5.5 0 1 0 .708-.708l-3-3z'/%3E%3Cpath d='M8 12a5 5 0 0 1-5-5V6.5a.5.5 0 0 0-1 0V7a6 6 0 0 0 6 6h.5a.5.5 0 0 0 0-1H8zm-2.646-2.646a.5.5 0 0 0 .708 0l3-3a.5.5 0 1 0-.708-.708l-1.75 1.75a.5.5 0 0 1-.708 0L4.646 6.354a.5.5 0 1 0-.708.708l3 3z'/%3E%3C/svg%3E");
        }

        /* 筛选相关样式 */
        .filter-container {
            position: relative;
            display: inline-block;
            width: 100%;
        }

        .filter-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            cursor: pointer;
        }

        .filter-icon {
            margin-left: 4px;
            font-size: 10px;
            color: #6b7280;
        }

        .filter-dropdown {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: white;
            border: 1px solid #d1d5db;
            border-radius: 4px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            padding: 6px;
            z-index: 1000;
            max-height: 250px;
            min-width: 180px;
            overflow-y: auto;
            font-size: 10px;
        }

        .filter-item {
            display: flex;
            align-items: center;
            padding: 3px 6px;
            cursor: pointer;
        }

            .filter-item:hover {
                background-color: #f3f4f6;
            }

            .filter-item input {
                margin-right: 6px;
                transform: scale(0.85);
            }

        .filter-actions {
            display: flex;
            justify-content: flex-end;
            margin-top: 6px;
            padding-top: 6px;
            border-top: 1px solid #d1d5db;
        }

            .filter-actions button {
                margin-left: 6px;
                padding: 3px 6px;
                border: 1px solid #d1d5db;
                border-radius: 4px;
                background: white;
                cursor: pointer;
                font-size: 9px;
            }

                .filter-actions button:hover {
                    background-color: #f3f4f6;
                }

        .filter-count {
            margin-left: 6px;
            font-size: 9px;
            color: #6b7280;
        }

        /* 高亮样式 */
        .highlight-other-cell {
            background-color: #E6F7FF !important;
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 页面标题 -->
        <header class="mb-6">
            <h1>排产跟踪</h1>
        </header>

        <!-- 日期筛选器 -->
        <div class="card mb-4">
            <div class="flex flex-wrap items-center gap-4">
                <div class="flex items-center gap-2">
                    <label for="start-date" class="form-label">日期范围:</label>
                    <input type="date" id="start-date" class="form-control">
                </div>
                <div class="flex items-center gap-2">
                    <span>至</span>
                    <input type="date" id="end-date" class="form-control">
                </div>
                <div class="flex items-center gap-2">
                    <button id="apply-date-filter" class="btn btn-primary">
                        <span class="icon icon-filter"></span> 应用日期筛选
                    </button>
                    <button id="refresh-btn" class="btn btn-secondary">
                        <span class="icon icon-refresh"></span> 重置所有筛选
                    </button>
                </div>
            </div>
        </div>

        <!-- 生产排产表格 - 添加专用类名 -->
        <div class="card schedule-card">
            <h2>生产排产跟踪表</h2>

            <!-- 表格容器 -->
            <div class="table-wrapper">
                <table id="production-schedule-table" class="excel-table">
                    <thead>
                        <tr>
                            <!-- 左侧列表头 -->
                            <th class="col-customer-order">
                                <div class="filter-container">
                                    <div class="filter-header" data-column="customerOrderNumber">
                                        <span>客户订单号</span>
                                        <span class="filter-icon">▼</span>
                                    </div>
                                </div>
                            </th>
                            <th class="col-work-order">
                                <div class="filter-container">
                                    <div class="filter-header" data-column="workOrderNumber">
                                        <span>工令号</span>
                                        <span class="filter-icon">▼</span>
                                    </div>
                                </div>
                            </th>
                            <th class="col-customer">
                                <div class="filter-container">
                                    <div class="filter-header" data-column="customer">
                                        <span>客户</span>
                                        <span class="filter-icon">▼</span>
                                    </div>
                                </div>
                            </th>
                            <th class="col-project">
                                <div class="filter-container">
                                    <div class="filter-header" data-column="projectName">
                                        <span>项目名称</span>
                                        <span class="filter-icon">▼</span>
                                    </div>
                                </div>
                            </th>
                            <th class="col-delivery-date">
                                <div class="filter-container">
                                    <div class="filter-header" data-column="customerDeliveryDate">
                                        <span>客户交期</span>
                                        <span class="filter-icon">▼</span>
                                    </div>
                                </div>
                            </th>
                            <th class="col-product">
                                <div class="filter-container">
                                    <div class="filter-header" data-column="productNumber">
                                        <span>产品编号</span>
                                        <span class="filter-icon">▼</span>
                                    </div>
                                </div>
                            </th>
                            <th class="col-order-qty">
                                <div class="filter-container">
                                    <div class="filter-header" data-column="orderQuantity">
                                        <span>订单数量</span>
                                        <span class="filter-icon">▼</span>
                                    </div>
                                </div>
                            </th>
                            <th class="col-process">
                                <div class="filter-container">
                                    <div class="filter-header" data-column="keyProcess">
                                        <span>关键工序</span>
                                        <span class="filter-icon">▼</span>
                                    </div>
                                </div>
                            </th>
                            <th class="col-category">
                                <div class="filter-container">
                                    <div class="filter-header" data-column="category">
                                        <span>区分</span>
                                        <span class="filter-icon">▼</span>
                                    </div>
                                </div>
                            </th>
                            <th class="col-quantity">
                                <div class="filter-container">
                                    <div class="filter-header" data-column="quantity">
                                        <span>数量</span>
                                        <span class="filter-icon">▼</span>
                                    </div>
                                </div>
                            </th>

                            <!-- 右侧日期列表头将通过JavaScript动态生成 -->
                            <th id="date-headers" colspan="31">
                                <!-- 日期表头将通过JavaScript动态生成 -->
                            </th>
                        </tr>
                    </thead>
                    <tbody id="table-body">
                        <!-- 表格内容将通过JavaScript动态生成 -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <script>
        // 优化后的数据结构 - 避免重复信息
        const mockProductionSchedule = [
          // 工令1：智能控制系统升级项目
          {
            workOrderInfo: {
                id: 1,
                customerOrderNumber: 'HX31-202500001',
                workOrderNumber: '25001',
                customer: '10607（ND）',
                projectName: '智能控制系统升级项目',
                customerDeliveryDate: '2025-11-30',
                productNumber: 'P-2025-001',
                orderQuantity: 100
            },
            processes: [
              // 冷加工 - 计划
              {
                keyProcess: '冷加工',
                category: '计划',
                dailySchedule: {
                  '2025-11-01': 10,
                  '2025-11-02': 10,
                  '2025-11-03': 10,
                  '2025-11-06': 10,
                  '2025-11-07': 10,
                  '2025-11-08': 10,
                  '2025-11-09': 10,
                  '2025-11-10': 10,
                }
              },
              // 冷加工 - 实际
              {
                keyProcess: '冷加工',
                category: '实际',
                dailySchedule: {
                  '2025-11-01': 10,
                  '2025-11-02': 10,
                  '2025-11-03': 10,
                  '2025-11-06': 10,
                  '2025-11-07': 10,
                  '2025-11-08': 9,
                  '2025-11-09': 8,
                  '2025-11-10': 8,
                }
              },
              // 箱体完工 - 计划
              {
                keyProcess: '箱体完工',
                category: '计划',
                dailySchedule: {
                  '2025-11-04': 10,
                  '2025-11-05': 10,
                  '2025-11-06': 10,
                  '2025-11-07': 10,
                  '2025-11-08': 10,
                  '2025-11-09': 10,
                  '2025-11-10': 10,
                  '2025-11-11': 10,
                }
              },
              // 箱体完工 - 实际
              {
                keyProcess: '箱体完工',
                category: '实际',
                dailySchedule: {
                  '2025-11-04': 8,
                  '2025-11-05': 8,
                  '2025-11-06': 10,
                  '2025-11-07': 9,
                  '2025-11-08': 9,
                  '2025-11-09': 8,
                  '2025-11-10': 7,
                  '2025-11-11': 6,
                }
              },
              // 容量测试 - 计划
              {
                keyProcess: '容量测试',
                category: '计划',
                dailySchedule: {
                  '2025-11-08': 10,
                  '2025-11-09': 10,
                  '2025-11-10': 10,
                  '2025-11-11': 10,
                  '2025-11-12': 10,
                  '2025-11-13': 10,
                  '2025-11-14': 10,
                  '2025-11-15': 10,
                }
              },
              // 容量测试 - 实际
              {
                keyProcess: '容量测试',
                category: '实际',
                dailySchedule: {
                  '2025-11-08': 8,
                  '2025-11-09': 8,
                  '2025-11-10': 7,
                  '2025-11-11': 7,
                  '2025-11-12': 6,
                  '2025-11-13': 6,
                  '2025-11-14': 6,
                  '2025-11-15': 7,
                }
              }
            ]
          },
          {
            workOrderInfo: {
                id: 1,
                customerOrderNumber: 'HX31-202500001',
                workOrderNumber: '25009',
                customer: '10607（ND）',
                projectName: '智能控制系统升级项目',
                customerDeliveryDate: '2025-11-30',
                productNumber: 'P-2025-001',
                orderQuantity: 100
            },
            processes: [
              // 冷加工 - 计划
              {
                keyProcess: '冷加工',
                category: '计划',
                dailySchedule: {
                  '2025-11-01': 10,
                  '2025-11-02': 10,
                  '2025-11-03': 10,
                  '2025-11-06': 10,
                  '2025-11-07': 10,
                  '2025-11-08': 10,
                  '2025-11-09': 10,
                  '2025-11-10': 10,
                }
              },
              // 冷加工 - 实际
              {
                keyProcess: '冷加工',
                category: '实际',
                dailySchedule: {
                  '2025-11-01': 10,
                  '2025-11-02': 10,
                  '2025-11-03': 10,
                  '2025-11-06': 10,
                  '2025-11-07': 10,
                  '2025-11-08': 9,
                  '2025-11-09': 8,
                  '2025-11-10': 8,
                }
              },
              // 箱体完工 - 计划
              {
                keyProcess: '箱体完工',
                category: '计划',
                dailySchedule: {
                  '2025-11-04': 10,
                  '2025-11-05': 10,
                  '2025-11-06': 10,
                  '2025-11-07': 10,
                  '2025-11-08': 10,
                  '2025-11-09': 10,
                  '2025-11-10': 10,
                  '2025-11-11': 10,
                }
              },
              // 箱体完工 - 实际
              {
                keyProcess: '箱体完工',
                category: '实际',
                dailySchedule: {
                  '2025-11-04': 8,
                  '2025-11-05': 8,
                  '2025-11-06': 10,
                  '2025-11-07': 9,
                  '2025-11-08': 9,
                  '2025-11-09': 8,
                  '2025-11-10': 7,
                  '2025-11-11': 6,
                }
              },
              // 容量测试 - 计划
              {
                keyProcess: '容量测试',
                category: '计划',
                dailySchedule: {
                  '2025-11-08': 10,
                  '2025-11-09': 10,
                  '2025-11-10': 10,
                  '2025-11-11': 10,
                  '2025-11-12': 10,
                  '2025-11-13': 10,
                  '2025-11-14': 10,
                  '2025-11-15': 10,
                }
              },
              // 容量测试 - 实际
              {
                keyProcess: '容量测试',
                category: '实际',
                dailySchedule: {
                  '2025-11-08': 8,
                  '2025-11-09': 8,
                  '2025-11-10': 7,
                  '2025-11-11': 7,
                  '2025-11-12': 6,
                  '2025-11-13': 6,
                  '2025-11-14': 6,
                  '2025-11-15': 7,
                }
              }
            ]
          },
          // 工令2：新型传感器研发项目
          {
            workOrderInfo: {
                id: 7,
                customerOrderNumber: 'HX31-202500002',
                workOrderNumber: '25002',
                customer: '10608（ABC）',
                projectName: '新型传感器研发项目',
                customerDeliveryDate: '2025-12-15',
                productNumber: 'P-2025-002',
                orderQuantity: 50
            },
            processes: [
              // 冷加工 - 计划
              {
                keyProcess: '冷加工',
                category: '计划',
                dailySchedule: {
                  '2025-11-10': 5,
                  '2025-11-11': 5,
                  '2025-11-12': 5,
                  '2025-11-13': 5,
                  '2025-11-14': 5,
                  '2025-11-17': 5,
                  '2025-11-18': 5,
                  '2025-11-19': 5,
                }
              },
              // 冷加工 - 实际
              {
                keyProcess: '冷加工',
                category: '实际',
                dailySchedule: {
                  '2025-11-10': 5,
                  '2025-11-11': 5,
                  '2025-11-12': 5,
                  '2025-11-13': 5,
                  '2025-11-14': 4,
                  '2025-11-17': 4,
                  '2025-11-18': 5,
                  '2025-11-19': 5,
                }
              },
              // 箱体完工 - 计划
              {
                keyProcess: '箱体完工',
                category: '计划',
                dailySchedule: {
                  '2025-11-15': 5,
                  '2025-11-16': 5,
                  '2025-11-17': 5,
                  '2025-11-18': 5,
                  '2025-11-19': 5,
                  '2025-11-20': 5,
                  '2025-11-21': 5,
                  '2025-11-22': 5,
                }
              },
              // 箱体完工 - 实际
              {
                keyProcess: '箱体完工',
                category: '实际',
                dailySchedule: {
                  '2025-11-15': 4,
                  '2025-11-16': 4,
                  '2025-11-17': 5,
                  '2025-11-18': 5,
                  '2025-11-19': 4,
                  '2025-11-20': 4,
                  '2025-11-21': 5,
                  '2025-11-22': 4,
                }
              },
              // 容量测试 - 计划
              {
                keyProcess: '容量测试',
                category: '计划',
                dailySchedule: {
                  '2025-11-20': 5,
                  '2025-11-21': 5,
                  '2025-11-22': 5,
                  '2025-11-23': 5,
                  '2025-11-24': 5,
                  '2025-11-25': 5,
                  '2025-11-26': 5,
                  '2025-11-27': 5,
                }
              },
              // 容量测试 - 实际
              {
                keyProcess: '容量测试',
                category: '实际',
                dailySchedule: {
                  '2025-11-20': 4,
                  '2025-11-21': 4,
                  '2025-11-22': 4,
                  '2025-11-23': 4,
                  '2025-11-24': 3,
                  '2025-11-25': 3,
                  '2025-11-26': 4,
                  '2025-11-27': 4,
                }
              }
            ]
          }
        ];

        // 将优化后的数据结构转换为平铺结构，便于前端处理
        function flattenProductionData(productionData) {
          const flattenedData = [];

          productionData.forEach(workOrder => {
            workOrder.processes.forEach(process => {
              // 计算每个工序的总数量（前端计算）
              const quantity = Object.values(process.dailySchedule).reduce((sum, qty) => sum + qty, 0);

              flattenedData.push({
                id: process.id,
                customerOrderNumber: workOrder.workOrderInfo.customerOrderNumber,
                workOrderNumber: workOrder.workOrderInfo.workOrderNumber,
                customer: workOrder.workOrderInfo.customer,
                projectName: workOrder.workOrderInfo.projectName,
                customerDeliveryDate: workOrder.workOrderInfo.customerDeliveryDate,
                productNumber: workOrder.workOrderInfo.productNumber,
                orderQuantity: workOrder.workOrderInfo.orderQuantity,
                keyProcess: process.keyProcess,
                category: process.category,
                quantity: quantity, // 前端计算
                dailySchedule: process.dailySchedule
              });
            });
          });

          return flattenedData;
        }

        // 计算各工序的汇总数据
        function calculateSummaryData(data, filterConditions) {
            const processes = ['冷加工', '箱体完工', '容量测试'];
            const categories = ['计划', '实际'];
            const summaries = [];

            let id = 100; // 汇总行ID从100开始，避免与项目数据冲突

            // 首先应用筛选条件应用到所有数据
            let filteredData = [...data];
            if (filterConditions) {
                Object.keys(filterConditions).forEach(column => {
                    const values = filterConditions[column];
                    filteredData = filteredData.filter(item => {
                        // 统一将项目值和筛选值都转换为字符串进行比较
                        const itemValue = item[column].toString();
                        return values.includes(itemValue);
                    });
                });
            }

            processes.forEach(process => {
                categories.forEach(category => {
                    // 筛选相同工序和类别的数据
                    const processCategoryData = filteredData.filter(item =>
                        item.keyProcess === process && item.category === category
                    );

                    // 计算总数量
                    const totalQuantity = processCategoryData.reduce((sum, item) => sum + item.quantity, 0);

                    // 计算每日排产总和
                    const dailySchedule = {};
                    processCategoryData.forEach(item => {
                        Object.keys(item.dailySchedule).forEach(date => {
                            if (!dailySchedule[date]) {
                                dailySchedule[date] = 0;
                            }
                            dailySchedule[date] += item.dailySchedule[date];
                        });
                    });

                    // 只有当有数据时才添加汇总行
                    if (processCategoryData.length > 0) {
                        summaries.push({
                            id: id++,
                            isSummary: true, // 标记为汇总行
                            keyProcess: process,
                            category: category,
                            quantity: totalQuantity,
                            dailySchedule: dailySchedule
                        });
                    }
                });
            });

            return summaries;
        }

        // 格式化日期为 YYYY-MM-DD 格式
        function formatDate(date) {
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0');
          const day = String(date.getDate()).padStart(2, '0');
          return `${year}-${month}-${day}`;
        }

        // 获取当前月份的第一天
        function getFirstDayOfMonth() {
          const today = new Date();
          return new Date(today.getFullYear(), today.getMonth(), 1);
        }

        // 获取当前月份的最后一天
        function getLastDayOfMonth() {
          const today = new Date();
          return new Date(today.getFullYear(), today.getMonth() + 1, 0);
        }

        // 获取指定日期范围内的所有日期
        function getDatesInRange(startDate, endDate) {
          const dates = [];
          const currentDate = new Date(startDate);

          while (currentDate <= endDate) {
            const dateStr = formatDate(currentDate);
            const dayOfWeek = currentDate.getDay();
            const isWeekend = dayOfWeek === 0 || dayOfWeek === 6;

            dates.push({
              date: dateStr,
              day: currentDate.getDate(),
              dayOfWeek: dayOfWeek,
              isWeekend: isWeekend
            });

            currentDate.setDate(currentDate.getDate() + 1);
          }

          return dates;
        }

        // 渲染日期表头
        function renderDateHeaders(startDate, endDate) {
          const dateHeadersContainer = document.getElementById('date-headers');
          const rangeDates = getDatesInRange(startDate, endDate);

          // 清空表头
          dateHeadersContainer.innerHTML = '';

          // 渲染日期表头
          rangeDates.forEach(dateInfo => {
            const th = document.createElement('th');
            th.className = `date-column ${dateInfo.isWeekend ? 'weekend' : ''}`;

            // 格式化日期显示（仅显示日）
            th.innerHTML = `
              <div class="text-sm font-medium">${dateInfo.day}</div>
              <div class="text-xs text-gray-500">
                ${dateInfo.dayOfWeek === 0 ? '日' :
                  dateInfo.dayOfWeek === 1 ? '一' :
                  dateInfo.dayOfWeek === 2 ? '二' :
                  dateInfo.dayOfWeek === 3 ? '三' :
                  dateInfo.dayOfWeek === 4 ? '四' :
                  dateInfo.dayOfWeek === 5 ? '五' : '六'}
              </div>
            `;

            dateHeadersContainer.appendChild(th);
          });

          // 更新日期列的colspan
          dateHeadersContainer.colSpan = rangeDates.length;
        }

        // 清除所有高亮
        function clearHighlights() {
            document.querySelectorAll('.highlight-other-cell').forEach(el => {
                el.classList.remove('highlight-other-cell');
            });
        }

        // 高亮行中除点击单元格外的所有单元格
        function highlightOtherCellsInRow(clickedCell) {
            // 清除之前的高亮
            clearHighlights();

            // 获取当前行
            const row = clickedCell.parentElement;

            // 获取当前行中的所有单元格
            const cells = Array.from(row.children);

            // 遍历所有单元格，高亮除点击单元格外的其他单元格
            cells.forEach(cell => {
                if (cell !== clickedCell) {
                    cell.classList.add('highlight-other-cell');
                }
            });
        }

        // 确保可以滚动到最右侧
        function ensureFullScrollability() {
            const tableWrapper = document.querySelector('.table-wrapper');
            const table = document.getElementById('production-schedule-table');

            // 确保表格容器有足够的宽度
            setTimeout(() => {
                // 触发一次滚动以更新滚动条位置
                tableWrapper.scrollLeft = 0;
                setTimeout(() => {
                    // 使用表格的实际宽度来设置滚动位置
                    tableWrapper.scrollLeft = table.scrollWidth - tableWrapper.clientWidth;
                }, 100);
            }, 100);
        }

        // 渲染表格内容
        function renderTableContent(data, startDate, endDate, filterConditions) {
          const tableBody = document.getElementById('table-body');
          const rangeDates = getDatesInRange(startDate, endDate);

          // 直接使用已筛选的数据data
          let filteredData = [...data];

          // 计算汇总数据
          const summaryData = calculateSummaryData(filteredData, filterConditions);

          // 汇总数据在前，项目数据在后
          const allData = [...summaryData, ...filteredData];

          // 清空表格内容
          tableBody.innerHTML = '';

          // 渲染每一行数据
          let previousWorkOrder = null;
          allData.forEach((item, index) => {
            const tr = document.createElement('tr');
            tr.dataset.id = item.id;

            // 如果是汇总行，添加特殊样式
            if (item.isSummary) {
                tr.classList.add('summary-row');
            }

            // 调整分隔线位置，使其向下移动一行
            if (index === summaryData.length) {
                tr.classList.add('summary-separator');
            }

            // 左侧列内容
            if (item.isSummary) {
                // 汇总行 - 合并前7列显示"Total"
                tr.innerHTML = `
                    <td class="col-customer-order" colspan="7" style="text-align: center; font-weight: bold;">Total</td>
                    <td class="col-process">${item.keyProcess}</td>
                    <td class="col-category">
                        <span class="status-tag ${
                          item.category === '计划' ? 'status-planned' :
                          'status-actual'
                        }">
                          ${item.category}
                        </span>
                    </td>
                    <td class="col-quantity">${item.quantity}</td>
                `;
            } else {
                // 普通行 - 在不同工令之间添加分隔线
                if (previousWorkOrder && previousWorkOrder !== item.workOrderNumber) {
                    const separatorRow = document.createElement('tr');
                    separatorRow.classList.add('work-order-separator');
                    separatorRow.innerHTML = `<td colspan="${10 + rangeDates.length}"></td>`;
                    tableBody.appendChild(separatorRow);
                }

                tr.innerHTML = `
                    <td class="col-customer-order">
                      ${item.customerOrderNumber}
                    </td>
                    <td class="col-work-order">${item.workOrderNumber}</td>
                    <td class="col-customer">${item.customer}</td>
                    <td class="col-project">${item.projectName}</td>
                    <td class="col-delivery-date">${item.customerDeliveryDate}</td>
                    <td class="col-product">${item.productNumber}</td>
                    <td class="col-order-qty">${item.orderQuantity}</td>
                    <td class="col-process">${item.keyProcess}</td>
                    <td class="col-category">
                        <span class="status-tag ${
                          item.category === '计划' ? 'status-planned' :
                          'status-actual'
                        }">
                          ${item.category}
                        </span>
                    </td>
                    <td class="col-quantity">${item.quantity}</td>
                `;

                // 更新上一个工令号
                previousWorkOrder = item.workOrderNumber;
            }

            // 右侧日期列内容
            rangeDates.forEach(dateInfo => {
              const td = document.createElement('td');
              td.className = `date-column ${dateInfo.isWeekend ? 'weekend' : ''}`;

              const scheduleData = item.dailySchedule ? item.dailySchedule[dateInfo.date] : 0;
              const qty = scheduleData || 0;

              // 如果有数量，显示并添加背景色
              if (qty > 0) {
                // 创建数量容器
                const qtyContainer = document.createElement('div');
                qtyContainer.className = 'schedule-qty-container';

                // 数量显示
                const qtyEl = document.createElement('div');
                qtyEl.className = item.category === '计划' ? 'planned-qty' : 'actual-qty';
                qtyEl.textContent = qty;
                qtyEl.title = `${item.category}: ${qty} 件`;

                // 根据类型设置不同的背景色
                if (item.category === '计划') {
                  td.classList.add('schedule-planned');
                } else {
                  td.classList.add('schedule-actual');
                }

                qtyContainer.appendChild(qtyEl);
                td.appendChild(qtyContainer);

                // 添加悬停提示
                td.title = `${dateInfo.date}\n${item.category}: ${qty} 件`;
              }

              tr.appendChild(td);
            });

            // 为每个单元格添加点击事件 - 只高亮行中其他单元格
            Array.from(tr.children).forEach(cell => {
                cell.addEventListener('click', function() {
                    highlightOtherCellsInRow(this);
                });
            });

            tableBody.appendChild(tr);
          });

          // 为表头添加点击事件
          const headerCells = document.querySelectorAll('#production-schedule-table th');
          headerCells.forEach(cell => {
              cell.addEventListener('click', function() {
                  highlightOtherCellsInRow(this);
              });
          });

          // 表格渲染完成后确保可以滚动到最右侧
          ensureFullScrollability();
        }

        // 初始化页面
        function initPage() {
          const startDateInput = document.getElementById('start-date');
          const endDateInput = document.getElementById('end-date');
          const applyFilterBtn = document.getElementById('apply-date-filter');
          const refreshBtn = document.getElementById('refresh-btn');

          // 设置默认日期范围为当月
          const today = new Date();
          const firstDay = getFirstDayOfMonth();
          const lastDay = getLastDayOfMonth();

          startDateInput.value = formatDate(firstDay);
          endDateInput.value = formatDate(lastDay);

          // 存储筛选条件
          let filterConditions = {};

          // 获取所有唯一值用于筛选
          const getUniqueValues = (column) => {
              const values = new Set();

              // 使用扁平化后的数据获取唯一值
              const flattenedData = flattenProductionData(mockProductionSchedule);
              flattenedData.forEach(item => {
                  if (item[column] !== undefined) {
                      values.add(item[column].toString());
                  }
              });

              return Array.from(values).sort();
          };

          // 创建筛选下拉框
          const createFilterDropdown = (column, container) => {
              // 移除已存在的下拉框
              const existingDropdown = container.querySelector('.filter-dropdown');
              if (existingDropdown) {
                  existingDropdown.remove();
              }

              // 创建下拉框容器
              const dropdown = document.createElement('div');
              dropdown.className = 'filter-dropdown';

              // 获取唯一值
              const uniqueValues = getUniqueValues(column);

              // 添加搜索框
              const searchInput = document.createElement('input');
              searchInput.type = 'text';
              searchInput.placeholder = '搜索...';
              searchInput.className = 'w-full p-2 mb-2 border rounded';
              dropdown.appendChild(searchInput);

              // 添加全选/取消全选
              const selectAllDiv = document.createElement('div');
              selectAllDiv.className = 'filter-item';

              // 检查是否所有选项都被选中
              const columnFilter = filterConditions[column] || [];
              const allSelected = columnFilter.length === 0 || columnFilter.length === uniqueValues.length;

              selectAllDiv.innerHTML = `
                  <input type="checkbox" id="selectAll-${column}" ${allSelected ? 'checked' : ''}>
                  <label for="selectAll-${column}">全选</label>
              `;
              dropdown.appendChild(selectAllDiv);

              // 添加分隔线
              const divider = document.createElement('div');
              divider.className = 'border-t border-gray-200 my-2';
              dropdown.appendChild(divider);

              // 添加筛选选项
              const valuesContainer = document.createElement('div');

              uniqueValues.forEach(value => {
                  const itemDiv = document.createElement('div');
                  itemDiv.className = 'filter-item';

                  // 检查是否已选中
                  const isSelected = !filterConditions[column] ||
                                    filterConditions[column].length === 0 ||
                                    filterConditions[column].includes(value);

                  itemDiv.innerHTML = `
                      <input type="checkbox" id="${column}-${value}" value="${value}" ${isSelected ? 'checked' : ''}>
                      <label for="${column}-${value}">${value}</label>
                  `;
                  valuesContainer.appendChild(itemDiv);
              });

              dropdown.appendChild(valuesContainer);

              // 添加操作按钮
              const actionsDiv = document.createElement('div');
              actionsDiv.className = 'filter-actions';
              actionsDiv.innerHTML = `
                  <button id="clear-${column}">清除筛选</button>
                  <button id="apply-${column}">应用筛选</button>
              `;
              dropdown.appendChild(actionsDiv);

              container.appendChild(dropdown);

              // 全选/取消全选事件
              document.getElementById(`selectAll-${column}`).addEventListener('change', function(e) {
                  const checked = e.target.checked;
                  valuesContainer.querySelectorAll('input[type="checkbox"]').forEach(checkbox => {
                      checkbox.checked = checked;
                  });
              });

              // 搜索功能
              searchInput.addEventListener('input', function(e) {
                  const searchTerm = e.target.value.toLowerCase();
                  valuesContainer.querySelectorAll('.filter-item').forEach(item => {
                      const label = item.querySelector('label').textContent.toLowerCase();
                      item.style.display = label.includes(searchTerm) ? 'flex' : 'none';
                  });
              });

              // 清除筛选
              document.getElementById(`clear-${column}`).addEventListener('click', function() {
                  // 清除该列的筛选条件
                  if (filterConditions[column]) {
                      delete filterConditions[column];
                  }

                  // 关闭下拉框
                  dropdown.remove();

                  // 重新渲染表格
                  applyFiltersAndRender();
              });

              // 应用筛选
              document.getElementById(`apply-${column}`).addEventListener('click', function() {
                  // 获取选中的值
                  const selectedValues = Array.from(valuesContainer.querySelectorAll('input[type="checkbox"]:checked'))
                      .map(checkbox => checkbox.value);

                  // 更新筛选条件
                  if (selectedValues.length === uniqueValues.length) {
                      // 如果全选，则清除该列的筛选条件
                      if (filterConditions[column]) {
                          delete filterConditions[column];
                      }
                  } else {
                      filterConditions[column] = selectedValues;
                  }

                  // 关闭下拉框
                  dropdown.remove();

                  // 重新渲染表格
                  applyFiltersAndRender();
              });

              return dropdown;
          };

          // 应用筛选并重新渲染表格
          const applyFiltersAndRender = () => {
              const startDate = new Date(startDateInput.value);
              const endDate = new Date(endDateInput.value);

              // 验证日期范围
              if (startDate > endDate) {
                  alert('开始日期不能晚于结束日期');
                  return;
              }

              // 扁平化数据
              let flattenedData = flattenProductionData(mockProductionSchedule);

              // 应用每个筛选条件
              Object.keys(filterConditions).forEach(column => {
                  const values = filterConditions[column];

                  flattenedData = flattenedData.filter(item => {
                      // 统一将项目值和筛选值都转换为字符串进行比较
                      const itemValue = item[column].toString();
                      return values.includes(itemValue);
                  });
              });

              // 重新渲染表格
              renderDateHeaders(startDate, endDate);
              renderTableContent(flattenedData, startDate, endDate, filterConditions);
              updateFilterIcons();
          };

          // 更新筛选图标状态
          const updateFilterIcons = () => {
              document.querySelectorAll('.filter-header').forEach(header => {
                  const column = header.dataset.column;
                  const icon = header.querySelector('.filter-icon');

                  if (filterConditions[column] && filterConditions[column].length > 0) {
                      icon.textContent = '▲';
                      icon.style.color = '#dc2626'; // 红色表示有筛选条件
                  } else {
                      icon.textContent = '▼';
                      icon.style.color = '#6b7280'; // 默认颜色
                  }
              });
          };

          // 初始化筛选功能
          const initFilters = () => {
              // 为每个筛选表头添加点击事件
              document.querySelectorAll('.filter-header').forEach(header => {
                  header.addEventListener('click', function(e) {
                      e.stopPropagation();

                      const column = this.dataset.column;
                      const container = this.parentElement;

                      // 关闭其他所有下拉框
                      document.querySelectorAll('.filter-dropdown').forEach(dropdown => {
                          if (!container.contains(dropdown)) {
                              dropdown.remove();
                          }
                      });

                      // 切换当前下拉框
                      const existingDropdown = container.querySelector('.filter-dropdown');
                      if (existingDropdown) {
                          existingDropdown.remove();
                      } else {
                          createFilterDropdown(column, container);
                      }
                  });
              });

              // 点击页面其他地方关闭下拉框
              document.addEventListener('click', function(e) {
                  const isClickInsideFilter = e.target.closest('.filter-container');
                  if (!isClickInsideFilter) {
                      document.querySelectorAll('.filter-dropdown').forEach(dropdown => {
                          dropdown.remove();
                      });
                  }
              });
          };

          // 初始化筛选
          initFilters();

          // 渲染初始表格
          const flattenedData = flattenProductionData(mockProductionSchedule);
          renderDateHeaders(firstDay, lastDay);
          renderTableContent(flattenedData, firstDay, lastDay, filterConditions);

          // 应用日期筛选按钮点击事件
          applyFilterBtn.addEventListener('click', applyFiltersAndRender);

          // 重置按钮点击事件
          refreshBtn.addEventListener('click', function() {
            // 重置日期范围为当月
            startDateInput.value = formatDate(firstDay);
            endDateInput.value = formatDate(lastDay);

            // 重置筛选条件
            filterConditions = {};

            // 重新渲染表格
            const flattenedData = flattenProductionData(mockProductionSchedule);
            renderDateHeaders(firstDay, lastDay);
            renderTableContent(flattenedData, firstDay, lastDay, filterConditions);
            updateFilterIcons();

            // 关闭所有下拉框
            document.querySelectorAll('.filter-dropdown').forEach(dropdown => {
                dropdown.remove();
            });
          });
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', initPage);
    </script>
</body>
</html>